package com.qiandw.security

import java.util

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.{ConfigAttribute, SecurityConfig}
import org.springframework.security.web.FilterInvocation
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource
import org.springframework.security.web.util.matcher.AntPathRequestMatcher
import org.springframework.stereotype.Component

import scala.collection.JavaConverters._

@Component
class MemberSecurityMetadataSource extends FilterInvocationSecurityMetadataSource {

  @Autowired
  var permissionSrv: PermissionSrv = _

  override def getAllConfigAttributes: util.Collection[ConfigAttribute] = {
    new util.HashSet[ConfigAttribute]()
  }

  override def getAttributes(o: scala.Any): util.Collection[ConfigAttribute] = {

    val attrs = new util.HashSet[ConfigAttribute]()

    val request = o.asInstanceOf[FilterInvocation].getHttpRequest

    val ps = permissionSrv.listPermission()

    ps.asScala.foreach(x => {

      val matcher = new AntPathRequestMatcher(x._1)

      if (matcher.matches(request)) {

        x._2.foreach(o => {
          attrs.add(new SecurityConfig(o))
        })

      }
    })

    attrs

  }

  override def supports(aClass: Class[_]): Boolean = true
}
